package com.loong.musicdemo.adapter;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.loong.musicdemo.R;

import java.util.List;

/**
 * 建议列表适配器
 */
public class SuggestionAdapter extends RecyclerView.Adapter<SuggestionAdapter.ViewHolder> {
    private List<String> suggestions;
    private Handler handler;

    public SuggestionAdapter(List<String> suggestions, Handler handler) {
        this.suggestions = suggestions;
        this.handler = handler;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_suggestion_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull SuggestionAdapter.ViewHolder holder, int position) {
        holder.search_keyword.setText(suggestions.get(position));

        holder.view.setOnClickListener(v -> {
            int pos = holder.getAdapterPosition();
            String keywords = suggestions.get(pos);
            if (!keywords.equals("暂无数据")) {
                Message msg = Message.obtain();
                msg.what = 3;
                msg.obj = keywords;
                handler.sendMessage(msg);
            }
        });

    }

    @Override
    public int getItemCount() {
        return suggestions.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView search_keyword;
        View view;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            view = itemView;
            search_keyword = itemView.findViewById(R.id.search_keyword);
        }
    }
}